import Store from "./utils/store.utils";
import BusUtils from "./utils/bus.utils";
import {deepExpand, deepMerge, ifObject} from "./utils/utils.utils";

const version = '0.1.0';

let $store = {}, $bus = new BusUtils();
let UIConfig = {
    homePath: '', // 首页路径
    useDefaultModal: false, // 默认使用小程序的弹层 如 wx.showModal wx.showToast wx.showLoading
    useDefaultTabBar: false, // 默认使用小程序的tabBar
    tabBar: [], //  如果使用小程序的tabBar 则该配置项无效
    showTabBarAllPage: false, // 所有页面都显示底部tabBar
    floorFooter: {
        show: true, // 显示底部信息
        icp: '晋ICP-0512', // 备案信息
        slogan: 'LDN-UI 为微信小程序定制UI组件', // 标语
        copyright: '', // 版权信息
        logo: '', //  logo图片地址
        link: 'https://developers.weixin.qq.com/miniprogram/dev/component/web-view.html', // 链接
    }, // 底部信息配置项
    theme: {
        theme: {
            main: '#dddddd',
            primary: '#00ff77',
            error: '#ff0000',
            warning: '#ffa500',
            success: '#00ff77',
            info: '#00ff77',
        },
        modal: {
            backgroundColor: '#ffffff',
            borderColor: '#f6f6f6',
            boxShadowColor: '#878787',
            maskColor: 'rgba(142,142,142,0.4)',
            textColor: '#000000',
            primaryColor: '#00ff77',
        },
        toast: {
            backgroundColor: '#ffffff',
            borderColor: '#f6f6f6',
            boxShadowColor: '#f6f6f6',
            maskColor: 'rgba(151,151,151,0.4)',
            textColor: '#000000',
        },
        loading: {
            backgroundColor: '#ffffff',
            borderColor: '#f6f6f6',
            boxShadowColor: '#f6f6f6',
            maskColor: 'rgba(151,151,151,0.4)',
            textColor: '#000000',
            closeColor: '#ffffff',
        },
        popup: {
            backgroundColor: '#ffffff',
            borderColor: '#f6f6f6',
            boxShadowColor: '#f6f6f6',
            maskColor: '#f6f6f6',
            textColor: '#000000',
            buttonColor: '#00ff77',
        },
        navBar: {
            backgroundColor: '#ffffff',
            borderColor: 'rgba(189,189,189,0.4)',
            boxShadowColor: '#f6f6f6',
            textColor: '#000000',
            iconColor: '#000000',
        },
        tabBar: {
            backgroundColor: '#ffffff',
            borderColor: '#cdcdcd',
            boxShadowColor: '#cdcdcd',
            textColor: '#000000',
            iconColor: '#000000',
            activeTextColor: '#00ff77',
            activeIconColor: '#00ff77',
            delimiterColor: '#d1d1d1',
        },
        form: {
            small: "32rpx",
            normal: "50rpx",
            large: "48rpx",
            switch: {
                checkedColor: '#ffffff',
                unCheckedColor: '#000000',
                checkedBgColor: '#1ab86a',
                unCheckedBgColor: '#cdcdcd',
                dotCheckedColor: '#00ff77',
                dotUnCheckedColor: '#6c6c6c',
            }
        },
        font: 32, // 字体大小 rpx单位 如需修改请修改
    },
};
let UIStore = {
    tabBarIndex: 0,
    modal: { show:false, title:'', content:'', mask: false, maskClose: false, showCancel:false, cancelText:'取消', confirmText:'确定', editable:false, placeholderText:'', success:(res) => {}},
    toast: { show:false, image: 'https://picsum.photos/200', content:'', duration: 1500, mask: false, loading: false, success:(res) => {} },
    /**
     * show 弹窗是否显示
     * content 弹窗内容
     * mask 是否显示遮罩
     * image 弹窗图片
     * timeout 弹窗超时
     * success 弹窗成功回调
     **/
    loading: { show:false, image: 'https://picsum.photos/200', content:'', box: false, timeout: 5000, mask: false, success:(res) => {} },
    popup: { show:false, title: '', content:'', duration: 1000, mask: false, maskClose: false, success:(res) => {} },
    form: { disabled: false, validate: false, },
};
let UIData = {};
let UIMethod = {
    showDialog({ title = '', content = '', mask= false, maskClose= false, showCancel = false, cancelText = '取消', confirmText = '确定', editable = false, placeholderText =  '', success = (res) => {}}) {
        const useDefaultModal = UIConfig.useDefaultModal;
        if (useDefaultModal) {
            wx.showModal({
                show: true,
                title: title,
                content: content,
                showCancel: showCancel,
                cancelText: cancelText,
                confirmText: confirmText,
                editable: editable,
                placeholderText: placeholderText,
                success: success
            });
        }
        else {
            $store.$r.map(item =>{
                if(item.is.indexOf('components/ui-modal/index') > -1 ){
                    //强制更新所有页面的successBack 为设定的success
                    item['modalSuccess'] = success;
                }
            })
            $store.setState({
                'modal.show': true,
                'modal.title' : title,
                'modal.content' : content,
                'modal.mask' : mask,
                'modal.maskClose' : maskClose,
                'modal.showCancel' : showCancel,
                'modal.cancelText' : cancelText,
                'modal.confirmText' : confirmText,
                'modal.editable' : editable,
                'modal.placeholderText' : placeholderText,
            });
        }
    },
    showToast({image = '', content ='', duration = 1500, mask = false, success = (res) => {}}) {
        const useDefaultModal = UIConfig.useDefaultModal;
        if (useDefaultModal) {
            wx.showToast({
                title: content,
                icon: image,
                duration: duration,
                mask: mask,
                success: success
            });
        }
        else {
            $store.$r.map(item =>{
                if(item.is.indexOf('components/ui-toast/index') > -1 ){
                    //强制更新所有页面的successBack 为设定的success
                    item['toastSuccess'] = success;
                }
            })
            $store.setState({
                'toast.show': true,
                'toast.content' : content,
                'toast.image' : image,
                'toast.mask' : mask,
                'toast.duration' : duration,
                'toast.success' : success,
                'toast.loading' : false,
            });
        }
    },
    showLoading({image = '', content ='', timeout = 5000, mask = false, success = (res) => {}}) {
        const useDefaultModal = UIConfig.useDefaultModal;
        if (useDefaultModal) {
            wx.showLoading({
                title: content,
                mask: mask,
                success: success
            });
        }
        else {
            $store.$r.map(item =>{
                if(item.is.indexOf('components/ui-loading/index') > -1 ){
                    //强制更新所有页面的successBack 为设定的success
                    item['loadingSuccess'] = success;
                }
            })
            $store.setState({
                'loading.show': true,
                'loading.content' : content,
                'loading.image' : image,
                'loading.mask' : mask,
                'loading.timeout' : timeout,
                'loading.success' : success,
            });
        }
    },
    hideLoading() {
        const useDefaultModal = UIConfig.useDefaultModal;
        if (useDefaultModal) {
            wx.hideLoading();
        }
        else {
            $store.setState({
                'loading.show': false,
            });
        }
    },
    showDrawer(option) {

    },
    hideDrawer(option) {

    },
    ifFirstPage() {
        return getCurrentPages().length === 1;
    },
    ifHomePage() {
        return "/" + this.is === UIConfig.homePath;
    },
    navigatePage(path) {
        const that = this;
        this.showLoading({
            content: '跳转中...',
            mask: true,
        })
        wx.navigateTo({
            url: path,
            complete: () => {
                let timer = 0;
                setTimeout(() => {
                    that.hideLoading();
                    clearTimeout(timer);
                }, 100);
            }
        });
    },
    onLoad(option) {
        if (!UIConfig.homePath) {
            throw new Error('请设置 homePath');
        }
        if (!UIConfig.useDefaultTabBar) {
            wx.hideTabBar();
        }
    },
};

class LdnUI {

    constructor({config, store, data, methods, storage}) {
        UIConfig  = deepMerge(UIConfig, config);
        UIStore = deepMerge(UIStore, store);
        UIMethod = {...UIMethod, ...methods};
        $store = new Store({
            state: {...UIStore}
        });
        let defaultStorage = wx.getStorageSync('defaultStorage');
        if (!defaultStorage) {
            let storageStr = deepExpand(storage);
            wx.setStorageSync("defaultStorage", storageStr);
        }
        this.validateConfig();
        this.initUi(data);
    }

    validateConfig() {

    }

    initUi(data) {
        const originPage = Page;
        const originComponent = Component;
        App.Page = function (o, ...args) {
            const data1 = deepMerge(UIData, data);
            o.data = deepMerge(data1, o.data);
            const pageMethods = [
                "data", "options", "behaviors", "onLoad", "onShow", "onReady", "onHide", "onUnload", "onRouteDone", "onPullDownRefresh",
                "onReachBottom", "onShareAppMessage", "onPageScroll", "onTabItemTap", "onResize", "onAddToFavorites", "onShareTimeline",
                "onSaveExitState"
            ]
            Object.keys(UIMethod).forEach((key) => {
                if (typeof UIMethod[key] === "function") {
                    if (pageMethods.some((item) => item === key)) {
                        const oldFun = o[key];
                        if (typeof oldFun === "function") {
                            o[key] = function (...args) {
                                UIMethod[key].call(this, ...args);
                                oldFun.call(this, ...args);
                            }
                        }
                    }else {
                        o[key] = UIMethod[key];
                    }
                }
            });
            return originPage(o, ...args);
        };

        App.Component = function (o, ...args) {
            const data1 = deepMerge(UIData, {config: { ...UIConfig }});
            o.data = deepMerge(data1, o.data);
            return originComponent(o, ...args);
        };

        try {
            Component = App.Component;
            Page = App.Page;
        } catch (e) { }

        console.log(
            `%c Ldn-UI 启动成功 %c 当前版本V` + version + `%c`,
            'background:#7DDA58; padding: 1px; border-radius: 3px 0 0 3px; color: #fff',
            'background:#000000; padding: 1px 5px; border-radius: 0 3px 3px 0; color: #fff; font-weight: bold;',
            'background:transparent'
        )
    }

    getStore() {
        return $store;
    }

    getBus() {
        return $bus;
    }

}

module.exports = {
    LdnUI
}